<?php
/**
 * Created by IntelliJ IDEA.
 * User: jimmyhsu
 * Date: 2017/5/8
 * Time: 23:12
 */
date_default_timezone_set("Asia/Shanghai");
include ("../Teacher/db/conn.php");
$username = $_POST['username'];
$password = $_POST['password'];
$b_id = $_POST['b_id'];
$course_id = $_POST['course_id'];
$title = $_POST['title'];
$author_id = $_POST['author'];
$content = $_POST['content'];
$has_image = $_POST['has_image'];
$remove_image = $_POST['remove_image'];
$sql = "select * from userinfo natural join takes where name='$username' and password='" . md5($password) . "' and course_id='$course_id' and position='assistant'";
$result = mysqli_query($cn, $sql);
if (mysqli_num_rows($result) > 0) {
    if (mb_strlen($title, 'UTF8') > 20 || mb_strlen($content, 'UTF8') > 100) {
        die('text length exceed');
    }

    $sql = "select image_url from bulletin where course_id='$course_id' and b_id=$b_id";
    $query = mysqli_query($cn, $sql);
    $row = mysqli_fetch_array($query);
    $original_image_url = $row['image_url'];
    $original_has_image = $original_image_url != '';

    $sql = "update bulletin set title='$title', content='$content', release_time='" . date("Y-m-d H:i:s") . "' where course_id='$course_id' and b_id=$b_id";
    $query = mysqli_query($cn, $sql);
    if ($remove_image == 'true' && $original_has_image) {
        $sql = "update bulletin set image_url='' where course_id='$course_id' and b_id=$b_id";
        mysqli_query($cn, $sql);
        $image_url = substr($original_image_url, 19);
        unlink($image_url);
        die('success');
    } else if ($has_image == 'true' && $original_has_image) {
        $image_url = substr($original_image_url, 19);
        unlink($image_url);
    }
    if ($query) {
        if ($has_image == 'true') {
            $allowedExts = array("jpeg", "jpg", "png");
            $temp = explode(".", $_FILES["image"]["name"]);
            $extension = end($temp);        // 获取文件后缀名
            if ($_FILES["image"]["size"] < 1024000   // 小于 1 Mb
                && in_array($extension, $allowedExts)) {
                if ($_FILES["image"]["error"] > 0) {
                    die("file_error");
                } else {
                    $file_name = $b_id . "." . $extension;
                    $file_dir = "image/" . $course_id;
                    if (!is_dir($file_dir)) {
                        mkdir($file_dir,0777,true);
                    }
                    move_uploaded_file($_FILES["image"]["tmp_name"], $file_dir . "/" . $file_name);
                    $sql = "update bulletin set image_url='phpprojects/course/image/$course_id/$file_name' where course_id='$course_id' and b_id=$b_id";
                    mysqli_query($cn, $sql);
                }
            } else {
                die("format_error");
            }
        }
        echo "success";
    } else {
        echo "db insert failed";
    }
} else {
    die ('permission denied');
}